// pages/order-detail/order-detail.js
import api from '../../utils/request/api'
const util = require('../../utils/util.js');
import {
  userOrder,pay
} from '../../utils/request/apiurl'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodList: {},
	openid:'',
	isPay: true, //支付方式弹窗
	showPayPwdInput: false, //是否展示密码输入层
	pwdVal: '', //输入的密码
	payFocus: true, //文本框焦点
	isPayPassword:'',//是否绑定支付密码
	payType:1, //支付方式
    totalPrice: 0,//总价格
    isPay: true, //支付方式弹窗
    orderIds: '',//手动退款的订单id
    payment: [{
      id: 0,
      name: '余额支付',
      value: '余额支付',
      checked: 'false'
    },
    {
      id: 1,
      name: '微信支付',
      value: '微信支付',
      checked: 'true'
    },
      // {
      // 	id: 2,
      // 	name: '积分兑换',
      // 	value: '积分兑换'
      // },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
	  // console.log(options)
    let id = options.orderId
    //获取订单详情
    api.post(userOrder.order, {
      orderNoAll: id
    }).then(res => {
      //回显支付方式
      if (res.payType == 0){
        //余额支付
        this.setData({
          payment: [{
            id: 0,
            name: '余额支付',
            value: '余额支付',
            checked: true
          },
          {
            id: 1,
            name: '微信支付',
            value: '微信支付',
            checked: false
          },
          ],
        })
      } else if (res.payType == 1){
        //微信支付
        this.setData({
          payment: [{
            id: 0,
            name: '余额支付',
            value: '余额支付',
            checked: false
          },
          {
            id: 1,
            name: '微信支付',
            value: '微信支付',
            checked: true
          },
          ],
        })
      }
      // console.log(res)
	  var list=res.list
	  var total1=0
	  for(var i=0;i<list.length;i++){
		  list[i]['checked']=false
		  var total=parseFloat(list[i].price/100*list[i].count)
		   total1+=total
		}
	  // debugger
      let a = res
      a.createTime = util.getLocalTime(a.createTime)
	  // console.log(util.getLocalDate1(a.createTime))
      if (a.payTime !== 0) {
        a.payTime = util.getLocalTime(a.payTime)
      }
      // a.courierPhone = a.courierPhone.substr(0, 3) + 'XXXX' + a.courierPhone.substr(a.courierPhone.length - 4)
      // a.consigneePhone = a.consigneePhone.substr(0, 3) + 'XXXX' + a.consigneePhone.substr(a.consigneePhone.length - 4)
      switch (a.pickUp) {
        case 0:
          a['pickup'] = "门店自提"
          break;
        case 1:
          a['pickup'] = "售货机"
          break;
      }
	  var  skuList=[]
	  var goodsSku=JSON.parse(res.list[0].goodsSku)
	  var skudata=''
	  for(var obj in goodsSku){
	  	if(skudata==''){
	  		skudata=goodsSku[obj]
	  	}else{
	  		skudata=skudata+'/'+goodsSku[obj]
	  	}
	  }
	  skuList.push(skudata)
	  a['skuList']=skuList
	  // console.log(a)
      this.setData({
		totalPrice:total1 ,
        goodList: a,
        payType:a.payType,
        openid:wx.getStorageSync('userInfo').xcxOpenid,
        isPayPassword:wx.getStorageSync('userInfo').isPayPassword
      })
	  
	  // console.log(this.data.goodList)
	  
	  
    }).catch(err => {
      wx.showToast({
        title: err.message,
        icon: 'none'
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
 onPullDownRefresh: function() {
 	// wx.showNavigationBarLoading() //在标题栏中显示加载
 	// this.onLoad()
 	// setTimeout(function() {
 	// 	wx.hideNavigationBarLoading() //完成停止加载
 	// 	wx.stopPullDownRefresh() //停止下拉刷新
 	// }, 1500);
 },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  // 忘记密码
  forgetPassWord(){
  	// var val = this.data.pwdVal;
  	wx.showModal({
  	  title: '忘记密码',
  	  content: '是否前往更换密码',
  	  success (res) {
  	    if (res.confirm) {
  			wx.redirectTo({
  				// url: '../personalInfo/personalInfo'
          url: '../comprehensivBind/comprehensivBind'
  			})
  	      // url: '../personalInfo/personalInfo'
  	    } else if (res.cancel) {
  			  this.setData({
  				showPayPwdInput: false,
  				payFocus: false,
  				pwdVal: ''
  			  });
  	    }
  	  }
  	})
  	
  },
  //选择支付方式
  paymentList() {
    this.setData({
      isPay: false
    })
  },
  //修改支付方式状态调用接口
  paySure() {
    this.setData({
      isPay: true
    })
    var source = {
      orderNoAll: this.data.goodList.orderNum,
      payType:this.data.payType
    }
    // console.log(source)
    api.post(pay.updateOrderPayType, source).then(res => {
      if(res.data.status == 0){
          console.log("成功",1)
      }
    }).catch(err => {
      console.log("失败")
    })
  },
  radioChange(e) {
    this.setData({
      payType: e.detail.value
    })
  },
  // 选择退款的订单
  checkboxChange(e){
	 // console.log(e,'eeeeeeeee') 
	var goodList = this.data.goodList
	// if(goodList.list[e.currentTarget.dataset.index].checked){
	// 	goodList.list[e.currentTarget.dataset.index].checked=true
	// }else{
	// 	
	// }
	goodList.list[e.currentTarget.dataset.index].checked=!goodList.list[e.currentTarget.dataset.index].checked||false	
	this.setData({
		goodList:goodList
	})
	// console.log(this.data.goodList)
	var orderIdList=[]
	// debugger
	for(var i=0;i<this.data.goodList.list.length;i++){   
		if(this.data.goodList.list[i].checked){
			orderIdList.push(this.data.goodList.list[i].id)
		}
		var string=orderIdList.join(',')
		// console.log(string)
		this.setData({
			orderIds:string
		})
	}
	// console.log(this.data.orderIds)
  }, 
  //显示支付密码输入层
  showInputLayer: function() {
  	this.setData({
  		showPayPwdInput: true,
  		payFocus: true,
  		pwdVal:''
  	});
  },
  // /**
  //  * 隐藏支付密码输入层
  //  */
  hidePayLayer: function() {
  	var val = this.data.pwdVal;
  	this.setData({
  		showPayPwdInput: false,
  		payFocus: false,
  		pwdVal: ''
  	});
  },
  /**
   * 获取焦点
   */
  getFocus: function(e) {
  	console.log(e)
  	this.setData({
  		payFocus: true
  	});
	// this.inputPwd()
  },
  /**
   * 输入密码监听
   */
  inputPwd: function(e) {
	  // console.log(e)
  	this.setData({
  		pwdVal: e.detail.value
  	});
    if (this.data.pwdVal.length==6){
      this.surePay()
    }
  	// console.log(this.data.pwdVal,'pwd')
  },
  // 去付款
  payGoods(){
	  // console.log(this.data.goodList.orderNum,'this.goodList.orderNum')
	  // 1为微信支付，0为余额
	  // console.log(this.data.payType)
	if(this.data.payType==0){
		if(this.data.isPayPassword==0){
			// wx.redirectTo({
			// 	url: '../personalInfo/personalInfo'
			// })
			// wx.showToast({
			// 	title: '请前往绑定支付密码',
			// 	icon: 'none',
			// 	duration: 2000
			// })
			wx.showToast({
			    title: '请前往绑定支付密码',
			    icon: 'none',
			    success: function () {
			      setTimeout(function() {
			        wx.redirectTo({
			        	// url: '../personalInfo/personalInfo'
                url: '../comprehensivBind/comprehensivBind'
			        })
			      }, 1000);
			    }
			});
		}else if(this.data.isPayPassword==1){
			this.showInputLayer()
		}
	}else if(this.data.payType==1){
		// console.log(this.data.goodList.orderNum,'this.goodList.orderNum')
		if (this.data.discountId != null && this.data.discountId != undefined && this.data.discountId != '') {
			var source = {
				// totalMoney:1,
				totalMoney:this.data.goodList.amountPrice,
				// totalMoney:this.data.goodList.price,
				orderNo: this.data.goodList.orderNum,
				openId: this.data.openid,
				discountId: this.data.goodList.discountId, //优惠券id
			}
		} else {
			var source = {
				// totalMoney:1,
				totalMoney:this.data.goodList.amountPrice,
				// totalMoney:this.data.goodList.price,
				orderNo: this.data.goodList.orderNum,
				openId: this.data.openid,
				// discountId:this.data.discountId,//优惠券id
			}
		}
		// console.log(source)
		api.post(pay.WxPay, source).then(res => {
			// console.log(res)
			if (res.payMessage.result_code == 'SUCCESS') {
				wx.requestPayment({
					'timeStamp': res.payMessage.time, //时间戳
					'nonceStr': res.payMessage.nonce_str, //随机串
					'package': res.payMessage.prepay_id, //数据包
					'signType': res.payMessage.signType, //签名方式
					'paySign': res.payMessage.sign,
					'notify_url':'http://backstage.dfbs-vm.com:443/boda/order/notify',
					success(res) {
						// console.log(res, 111)
						if (res.errMsg == 'requestPayment:ok') {
							// wx.navigateTo({
							// 	url: '../myOrder/myOrder?type=2'
							// })
							// wx.showToast({
							// 	title: '支付成功',
							// 	icon: 'none',
							// 	duration: 2000
							// })	
							wx.showToast({
							    title: '支付成功',
							    icon: 'none',
							    success: function () {
							      setTimeout(function() {
							        wx.redirectTo({
							        	url: '../myOrder/myOrder?type=2'
							        })
							      }, 1000);
							    }
							});
						}
					},
					fail(res) {
						wx.navigateBack({
						  delta:1
						})
					}
				})
			}
		}).catch(err => {
			// console.log(err)
			wx.showToast({
				title: err.message,
				icon: 'none'
			})
		})
	}	  
  },
  // 确定支付
  surePay(){
  	this.setData({
  		pwdVal:this.data.pwdVal,
  		// showPayPwdInput: false,
  	})
	// console.log(this.data.goodList.orderNum)
	// console.log(this.data.openid)
  	if(this.data.pwdVal.length==6){
  		if (this.data.discountId != null && this.data.discountId != undefined && this.data.discountId != "") {
  			var source = {
  				// totalMoney:1,
				totalMoney:this.data.goodList.amountPrice,
  				// totalMoney:this.data.goodList.price,
  				orderNo: this.data.goodList.orderNum,
  				openId: this.data.openid,
  				discountId: this.goodList.discountId, //优惠券id
  				// password: 123457, //支付密码
  				password:this.data.pwdVal,
  			}
  		} else {
  			var source = {
  				// totalMoney:1,
				totalMoney:this.data.goodList.amountPrice,
  				// totalMoney:this.data.goodList.price,
  				orderNo: this.data.goodList.orderNum,
  				openId: this.data.openid,
  				// password: 123457, //支付密码
  				password:this.data.pwdVal,
  			}
  		}
  		// console.log(source)
  		api.post(pay.BalancePay, source).then(res => {
  			// console.log(res,'resres')
  			var orderId = res.split(':')
  			// console.log(orderId, 333)
  			if (orderId[1] == 'OK') {
				wx.showToast({
				    title: '支付成功',
				    icon: 'none',
				    success: function () {
				      setTimeout(function() {
				        wx.redirectTo({
				        	url: '../myOrder/myOrder?type=2'
				        })
				      }, 1000);
				    }
				});
  				
  			}
  		}).catch(err => {
			// console.log(err)
			this.setData({
				showPayPwdInput: true,
				pwdVal:'',
				// payFocus:true
			})
  			wx.showToast({
  			    title: err.message,
  			    icon: 'none',
  			    // success: function () {
  			    //   setTimeout(function() {
  			    //     wx.redirectTo({
  			    //     	url: '../myOrder/myOrder?type=1'
  			    //     })
  			    //   }, 1000);
  			    // }
  			});
        this.hidePayLayer()
			// wx.redirectTo({
			// 	url: '../myOrder/myOrder?type=1'
			// })
  	// 		wx.showToast({
  	// 			title: '支付失败',
  	// 			icon: 'none',
  	// 			duration: 5000
  	// 		})	
  		})
  	}	
  },
  
  // 地址详情
  adressDetail() {
    wx.navigateTo({
      url: '../receiveing-adress/receiveing-adress'
    })
  },
  //删除订单
  deleteOrder() {
    let that = this
	let orderNum = that.data.goodList.orderNum
    wx.showModal({
      title: '删除订单',
      content: '是否确认删除这个订单？',
      success: function (res) {
        if (res.confirm) {
          api.post(userOrder.deleteOrder, {
            orderNOAll: orderNum
          }).then(res => {
            wx.redirectTo({
              url: '../myOrder/myOrder?type=0'
            })
          }).catch(err => {
            wx.showToast({
              title: err.message,
              icon: 'none'
            })
          })
        }
      }
    })
  },
  //取消订单
  cancelOrder(e) {	
    let that = this
	 let id = that.data.goodList.orderNum;
    wx.showModal({
      title: '取消订单',
      content: '是否确认取消这个订单？',
      success: function (res) {
        if (res.confirm) {
          api.post(userOrder.cancelOrder, {
            OrderNoAll: id,
            formId: e.detail.formId,
          }).then(res => {
            wx.redirectTo({
              url: '../myOrder/myOrder?type=1'
            })
          }).catch(err => {
            wx.showToast({
              title: err.message,
              icon: 'none'
            })
          })
        }
      }
    })
  },
  // 确认收货
  sureOrder(e) {
    let id = e.detail.value.input
  	let that = this
  	wx.showModal({
  	  title: '确认收货',
  	  content: '是否确定已收到货物？',
  	  success: function (res) {
  	    if (res.confirm) {
  	      api.post(userOrder.affirmOrder, {
  	        OrderNoAll: id,
  	        // uid: "da3bdf61cc1a409cafe573ea389c0e09" //测试uid
            uid: that.data.uid || wx.getStorageSync('userInfo').uid,
            formId: e.detail.formId
  	      }).then(res => {
  			wx.redirectTo({
  				url: '../myOrder/myOrder?type=4'
  			})
  	        // that.getList(1)
  	      }).catch(err => {
  	        wx.showToast({
  	          title: err.message,
  	          icon: 'none'
  	        })
  	      })
  	    }
  	  }
  	})
  },
  // 配送员电话
  telService(e) {
	wx.makePhoneCall({
		phoneNumber:e.currentTarget.dataset.courierphone
	})
  },
  // 手动退款
  refundOrder(e){
    console.log("手动退款",e)
    let orderNum = e.currentTarget.dataset['ordernum'] || e.detail.value.input
	 let that = this
	// console.log(that.data.orderIds)
	 if(that.data.orderIds.length>0){
		 wx.showModal({
		   title: '手动退款',
		   content: '一个订单只能退款一次,是否确定退款？',
		   success: function (res) {
		     if (res.confirm) {
		       api.post(userOrder.refundOrder, {
		         orderNoAll: orderNum,
		         uid: wx.getStorageSync('userInfo').uid,
		 		     orderIds:that.data.orderIds,
             formId: e.detail.formId,
		       }).then(res => { 
					  wx.showToast({
					      title: res,
					      icon: 'none',
					      success: function () {
					        setTimeout(function() {
					        wx.redirectTo({
					        	url: '../myOrder/myOrder?type=0'
					        }) 
					        }, 1000);
					      }
					  });
		       }).catch(err => {
				   
		         wx.showToast({
		           title: err.message,
		           icon: 'none'
		         })
		       })
		     }
		   }
		 })
	 }else{
		wx.showToast({
		    title: '请选择要退款的商品',
		    icon: 'none',
		    duration:2000,
		}); 
		return false
	 }
	  
	  
  },
})